function validate(form) {
	switch(form.name) {
		case "flight": return validateFlight(form);
		case "seats":  return validateSeats(form);
	}
}

function isValidByRegex(formElem, regex, errorId) {
	return setError(document.getElementById(errorId), regex.test(formElem.value));
}

function isValidRadio(formElem, errorId) {
	var hasOneSet = false;
	for (var i in formElem) {
		if (formElem[i].checked) hasOneSet = true;
	}
	return setError(document.getElementById(errorId), hasOneSet);
}

function setError(errorElement, bool) {
	errorElement.style.display = "none";
	if (!bool) {
		errorElement.style.display = "block";
	}
	return bool;
}

function validateFlight(form) {

	var validated = true;
	var bookdate = new Date(form.year.value, form.month.value, form.day.value, 0, 0, 0, 0);
	
	var dateError = document.getElementById("dateError");
	var pastError = document.getElementById("pastError");
	var twoWeeksError = document.getElementById("twoWeeksError");
	
	dateError.style.display = "none";
	pastError.style.display = "none";
	twoWeeksError.style.display = "none";
	
	
	if (bookdate.getFullYear() != form.year.value ||
		bookdate.getMonth() != form.month.value ||
		bookdate.getDate() != form.day.value) {
		
		validated = false;
		// set error (invalid date)
		dateError.style.display = "block";
	}
	
	if (bookdate.getTime() < tomor.getTime()) {
		validated = false;
		// set error (past date)
		pastError.style.display = "block";
	}
	
	if (bookdate.getTime() > (today.getTime() + 2*7*24*60*60*1000)) {
		validated = false;
		//set error (more than two weeks)
		twoWeeksError.style.display = "block";
	}
	
	return validated;
}

function validateSeats(form) {
	// TODO: check if expiration is future
	var a = isValidRadio(form.seat, "seatError");
	var b = isValidByRegex(form.firstName, /^[a-zA-Z]+$/g, "firstNameError");
	var c = isValidByRegex(form.lastName, /^[a-zA-Z]+$/g, "lastNameError"); // TODO: More chars?
	var d = isValidByRegex(form.ccNum, /^\d{4}-?\d{4}-?\d{4}-?\d{4}$/g, "ccNumError");
	var e = isValidByRegex(form.expMonth, /^\d{2}$/g, "expMonthError");
	var f = isValidByRegex(form.expYear, /^\d{2}$/g, "expYearError");
	var g = isValidByRegex(form.address, /^[0-9a-zA-Z.,\s]+$/g, "addressError");
	var h = isValidByRegex(form.city, /^[a-zA-Z]+$/g, "cityError");
	var i = isValidByRegex(form.province, /^[a-zA-Z]+$/g, "provinceError");
	var j = isValidByRegex(form.postalCode, /^[a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]$/g, "postalCodeError");
	return a && b && c && d && e && f && g && h && i && j;
}
